import React, { useState, useEffect, useRef, useLayoutEffect } from 'react'; // 这行必须写，不然报错，可能是eslint搞事情。
import { connect } from 'dva'; // connect用于组件连接models层数据
import { history } from 'umi';

import {
  Row,
  Col,
  Input,
  Form,
  DatePicker,
  Space,
  Tree,
  Table,
  Button,
  Modal,
  Switch,
  message,
  TreeSelect,
  Radio,
  Select,
  Spin,
} from 'antd';
const { confirm } = Modal;
const { RangePicker } = DatePicker;
const { TreeNode } = TreeSelect;
const { Search } = Input;
const {Option} = Select
import {
  SearchOutlined,
  PlusSquareOutlined,
  EditOutlined,
  DeleteOutlined,
  RedoOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  KeyOutlined,
  VerticalAlignBottomOutlined,
  VerticalAlignTopOutlined,
} from '@ant-design/icons';
import {
  listUser,
  changeUserStatus,
  getUser,
  delUser,
} from '@/api/system/user.js';
import { treeselect, deeps } from '@/api/system/dept.js';
import { addDateRange } from '@/utils/ruoyi.js';

import AddUserModalForm from '@/components/addUserModalForm.js';
import EditUserModalForm from '@/components/editUserModalForm.js';
import KeyUserModalForm from '@/components/keyUserModalForm.js';
import UserDragger from '@/components/upload/userDragger.jsx';

import { set } from 'js-cookie';

const SystemUserPage = ({ dept, dispatch }) => {
  const [form] = Form.useForm()
  const [userlist, setUserlist] = useState(null);
  const [queryParams, setQueryParams] = useState({
    //查询参数
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
  });
  const [total, setTotal] = useState(null);
  const [dateRange, setDateRange] = useState([]); //日期范围
  const [visible, setVisible] = useState(false); //添加用户布尔值
  const [editVisible, editSetVisible] = useState(false); //添加用户布尔值
  const [editkeyVisible, setEditkeyVisible] = useState(false); //添加用户布尔值
  const [treeData, setTreeData] = useState([]);
  const [switchStatus, setSwitchStatus] = useState(null); //用户状态
  const [mocktreedata, setMocktreedata] = useState([
    {
      key: 100,
      title: '若依科技',
      children: [
        {
          key: 101,
          title: '深圳总公司',
          children: [
            {
              key: 103,
              title: '研发部门',
            },
            {
              key: 104,
              title: '市场部门',
            },
            {
              key: 105,
              title: '测试部门',
            },
            {
              key: 106,
              title: '财务部门',
            },
            {
              key: 107,
              title: '运维部门',
            },
          ],
        },
        {
          key: 102,
          title: '长沙分公司',
          children: [
            {
              key: 108,
              title: '市场部门',
            },
            {
              key: 109,
              title: '财务部门',
            },
          ],
        },
      ],
    },
  ]);
  const [selectionType, setSelectionType] = useState('checkbox');
  const [deptName, setDeptName] = useState('');
  const [editid, seteditid] = useState(null);
  const [editState, setEditState] = useState(null);
  const [valueflag, setvalueFlag] = useState(false);
  const [userId, setUserId] = useState(null);
  const [selectedRowKey, setselectedRowKeys] = useState(''); //多选的id
  const [deleteS, setdeleteS] = useState(true); //多选删除是否激活
  const [loading, setLoading] = useState(false);




  useEffect(() => {
    initTree();
  }, []);

  useEffect(() => {
    initList(); //查询用户
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 400);
  }, [queryParams]);

  /** 查询用户列表 */
  const initList = () => {
    listUser(queryParams).then(res => {
      if (res.code == 200) {
        setUserlist(res.rows);
        setTotal(res.total);
      }
    });
  };
  /** 查询部门下拉树结构 */
  const initTree = () => {
    treeselect().then(resp => {
      if (resp.code == 200) {
        setTreeData(deeps(resp.data));
      }else if(resp.code==401){
        confirm({
          title: '系统提示',
          icon: <ExclamationCircleOutlined />,
          content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
          cancelText: '取消',
          okText: '确定',
          onOk() {
            history.push('/login')
          },
          onCancel() {
            console.log('重新登录');
          },
        });
      }
    })
  }
  //加载完成树形节点 触发  (未触发)
  const TreeExPandAll = (loadedKeys, { event, node }) => {
    console.log(loadedKeys, event, node);
  };

  /** 树形组件点击触发查询 */
  const onSelect = (selectedKeys, info) => {
    setQueryParams({
      deptId: info.node.id,
    });
  };
  // 树形节点搜索
  const onSearch = value => {
    if(value==''){
      initTree()
    }else{
      value=value.replace(/\s/g, "")
    }
    if (treeData.length) {
      treeData
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            setTreeData([item])
          }else{
            item.children.filter(v=>{
              if(v.title.indexOf(value)> -1){
                setTreeData([v])
              }else{
                if(v.children!=undefined){
                  v.children.filter(t=>{
                    if(t.title.indexOf(value)> -1){
                        setTreeData([t])
                    }
                  })
                }
              }
            })
          }
        })
    }
  }


  const onCheck = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
  };

  const columns = [
    {
      title: '用户编号',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '部门',
      dataIndex: ['dept', 'deptName'],
      key: 'dept.deptName',
    },
    {
      title: '手机号码',
      dataIndex: 'phonenumber',
      key: 'phonenumber',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status, record) => (
        <Switch
          defaultChecked={Number(status)}
          checked={Number(status)}
          onClick={nowStatus => {
            let textstate = nowStatus === true ? '启用' : '停用';
            confirm({
              title: `确认要${textstate}"${record.userName}用户吗?"`,
              icon: <ExclamationCircleOutlined />,
              cancelText: '取消',
              okText: '确定',
              onOk() {
                /** 更新用户状态 */
                changeUserStatus(record.userId, `${Number(nowStatus)}`).then(
                  res => {
                    if (res.code == 500) {
                      message.warning(res.msg);
                      return false;
                    } else if (res.code == 200) {
                      message.success(textstate + '成功');
                      initList(); //查询用户
                    }
                  },
                );
              },
              onCancel() {
                message.warning('取消成功');
              },
            });
          }}
        ></Switch>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      render: (status, record) => (
        <Space size="middle">
          <a onClick={() => editUserModel(status,record)}>
            <EditOutlined />
            修改
          </a>
          <a
            onClick={status => {
              confirm({
                title: `是否确认删除用户编号为${record.userId}用户吗?"`,
                icon: <ExclamationCircleOutlined />,
                cancelText: '取消',
                okText: '确定',
                onOk() {
                  /** 更新用户状态 */
                  delUser(record.userId).then(res => {
                    if (res.code == 500) {
                      message.warning(res.msg);
                      return false;
                    } else if (res.code == 200) {
                      message.success('删除用户编号成功');
                      initList();
                    }
                  });
                },
                onCancel() {
                  message.warning('取消成功');
                },
              });
            }}
          >
            <DeleteOutlined />
            删除
          </a>
          <a onClick={() => keyUserModel(status)}>
            <KeyOutlined />
            重置
          </a>
        </Space>
      ),
    },
  ];

  //添加用户模态框
  const showUserModal = () => {
    setVisible(true);
  };
  const hideUserModal = () => {
    setVisible(false);
  }
  //点击搜索
  const onFinish = values => {

    if(values.time!==undefined){
      const rangeValue = values['time'];

      setQueryParams({
        ...queryParams,
        userName:values.userName,
        phonenumber:values.phonenumber,
        status:values.status,
        beginTime:rangeValue[0].format('YYYY-MM-DD'),
        endTime:rangeValue[1].format('YYYY-MM-DD'),
      })
    }else{
      setQueryParams({
        ...queryParams,
        userName:values.userName,
        phonenumber:values.phonenumber,
        status:values.status,
      })
    }

  };

  //修改用户模态框
  const editUserModel = (status,record) => {
    setUserId(
      status.userId
    )


    editSetVisible(true);
  };
  const edithideUserModal = () => {
    editSetVisible(false);
  };

  //修改用户密码 模态框
  const keyUserModel = status => {
    setEditkeyVisible(true);

    setUserId(status.userId);
  };
  const keyHideUserModel = status => {
    setEditkeyVisible(false);
  };

  //分页页码改变回调
  const paginationChange = (page, pageSize) => {
    setQueryParams({
      pageNum: 1,
      pageSize: 10,
    });
  };

  //分页页码改变回调
  const pageSizeChange = (current, size) => {
    setQueryParams({
      ...queryParams,
      pageNum: current,
      pageSize: size,
    });
  };

  // Table 列表多选
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      if (selectedRowKeys == '') {
        setdeleteS(true);
      }
      setdeleteS(false);

      setselectedRowKeys(selectedRowKeys.join(','));
    },
    getCheckboxProps: record => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
  };

  //批量删除
  const deleteUsers = () => {
    delUser(selectedRowKey).then(res => {
      if (res.code == 500) {
        message.warning(res.msg);
        return false;
      } else if (res.code == 200) {
        message.success('删除用户编号成功');
        initList();
        setdeleteS(true);
      }
    });
  }

  //重置
  const Reload=()=>{

    setQueryParams({
      pageNum: 1,
      pageSize: 10,
    });

    form.resetFields()
  }

  return (
    <>
      <Row gutter={24}>
        <Col className="gutter-row" xs={24} xxl={4} span={4}>
          <div className="head-container">
            <Search
              style={{ marginBottom: 8 }}
              placeholder="请输入部门名称"
              onSearch={onSearch}
            />
          </div>

          <div className="head-container">
          <Spin spinning={loading}>
            {treeData.length && (
              <Tree
                onCheck={onCheck}
                onSelect={onSelect}
                treeData={treeData}
                autoExpandParent
                defaultExpandAll="true"
                // expandedKeys={['100']}
                // onLoad={TreeExPandAll}
              >
                {/* {renderTreeNodes(dept.treeData)} */}
              </Tree>
            )}
            </Spin>
          </div>
        </Col>
        <Col  xs={24} xxl={20} span={20}>
          <Form
          labelAlign="right"
          layout="horizontal"
          form={form}
          onFinish={onFinish}
          >
              <Row>
              <Col   className="userGrid">
              <Form.Item label="用户名称"  name="userName">
                <Input style={{ width: '240px' }} placeholder="请输入用户名称" />
              </Form.Item>
              <Form.Item label="手机号码" name="phonenumber">
                <Input style={{ width: '240px' }} placeholder="请输入手机号码" />
              </Form.Item>
              <Form.Item   label="状态" name="status" >
               <Select style={{ width: '240px' }} >
                <Option value={0}>停用</Option>
                <Option value={1}>正常</Option>
              </Select>
              </Form.Item>
              <Form.Item label="创建时间" name="time">
                <RangePicker  style={{ width: '240px' }} format="YYYY-MM-DD" />
              </Form.Item>
            </Col>
            <Col xs={24} xxl={20} span={20}>
            <Form.Item >
              <Button type="primary"
                icon={<SearchOutlined />}
                htmlType="submit"
                style={{marginRight:'16px'}}
                >
                搜索
              </Button>
              <Button icon={<ReloadOutlined />}  onClick={Reload}>
                重置
              </Button>
              </Form.Item>
              </Col>
            </Row>
          </Form>

          <Row gutter={[16, 16]}>
            <Col span={1.5}>
              <Button
                type="primary"
                icon={<PlusSquareOutlined />}
                onClick={showUserModal}
              >
                新增
              </Button>
            </Col>
            <Col span={1.5}>
              <Button
                danger="true"
                onClick={deleteUsers}
                disabled={deleteS}
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Col>

            <UserDragger queryParams={queryParams}></UserDragger>
          </Row>

          <Spin spinning={loading}>
            {userlist !== null && total && (
              <Table
                rowSelection={{
                  type: selectionType,
                  ...rowSelection,
                }}
                dataSource={userlist}
                columns={columns}
                rowKey={userlist => userlist.userId}
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: true,
                  defaultCurrent: 1,
                  onChange: paginationChange,
                  onShowSizeChange: pageSizeChange,
                  pageSizeOptions: [5, 8, 10],
                  total: total,
                }}
              />
            )}
          </Spin>
        </Col>
        {/* 添加用户模态框 */}
        <AddUserModalForm
          visible={visible}
          treeData={treeData}
          oninitList={initList}
          onhideUserModal={hideUserModal}
          onCancel={hideUserModal}
        />

        {/* 修改用户模态框 */}
        { setUserId !== null&&editVisible && (
          <EditUserModalForm
            visible={editVisible}
            treeData={treeData}
            oninitList={initList}
            onhideUserModal={edithideUserModal}
            onCancel={edithideUserModal}
            userId={userId}
          />
        )}

        {/*重置密码模态框*/}

        {setUserId !== null && (
          <KeyUserModalForm
            visible={editkeyVisible}
            oninitList={initList}
            onhideUserModal={keyHideUserModel}
            onCancel={keyHideUserModel}
            userId={userId}
          />
        )}
      </Row>
    </>
  );
};

const mapStateToProps = ({ dept }) => {
  return {
    dept,
  };
};

export default connect(mapStateToProps)(SystemUserPage);
